package com.hitsz.cdq;

import android.app.Fragment;
import android.app.FragmentManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.sql.Connection;
import java.sql.SQLException;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    public static String IP_ADDRESS_SERVER = "192.168.1.109";
    public static String PORT_SERVER = "1234";
    public static String USER = "root";
    public static String PASSWORD = "root";

    public static String APP_ACK_STATE = "app_ack_state";
    public static String APP_ACK_ALL = "app_ack_all";
    public static String DISCONNECT = "disconnect";
    private Toolbar toolbar;
    private FrameLayout content_frame;
    private LinearLayoutCompat content_layout;
    private TextView connect_state_tv;
    private EditText server_state_edt;
    private Button btn_connect, btn_clear;

    public static InputStream inputStream;//创建输入数据流
    public static OutputStream outputStream;//创建输出数据流

    private ClientSocket_thread mClientSocket_thread;
    private Receive_Thread mReceive_Thread;
    private Socket clientSocket;
    private Boolean isConnected, isClientSocket_threadWorking, isReceive_ThreadWorking;
    public static String data_from_server;
    public static CommonUtils dbUtils;

    private Connection mysql_conn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setSubtitle("系统状态");

        dbUtils = new CommonUtils(this);
//        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Snackbar.make(view, "等待添加功能", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//            }
//        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        content_layout = (LinearLayoutCompat) findViewById(R.id.content_layout);
        content_frame = (FrameLayout) findViewById(R.id.content_frame);

        connect_state_tv = (TextView) findViewById(R.id.connect_state_tv);
        server_state_edt = (EditText) findViewById(R.id.server_state_text);
        server_state_edt.setFocusable(false);
        isConnected = false;
        connect_state_tv.setText("未连接");
        btn_connect = (Button) findViewById(R.id.btn_connect);
        btn_connect.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (isConnected) {
                    stopClient();
                    btn_connect.setText("连接");
                } else {
                    startClient();
                    onConn(v);
                    btn_connect.setText("断开");
                }
            }
        });

        btn_clear = (Button) findViewById(R.id.btn_clear);
        btn_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                server_state_edt.setText("");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mysql_conn != null) {
            try {
                mysql_conn.close();
            } catch (SQLException e) {
                mysql_conn = null;
            } finally {
                mysql_conn = null;
            }
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            toolbar.setSubtitle("系统状态");
            content_layout.setVisibility(View.VISIBLE);
            content_frame.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        FragmentManager fm = getFragmentManager();
        if (id == R.id.action_settings) {
            toolbar.setSubtitle("设置");
            content_layout.setVisibility(View.GONE);
            content_frame.setVisibility(View.VISIBLE);
            Fragment fg = new SettingFragment();
            fm.beginTransaction().replace(R.id.content_frame, fg).commit();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        FragmentManager fm = getFragmentManager();
        if (id == R.id.nav_index) {
            toolbar.setSubtitle("系统状态");
            content_layout.setVisibility(View.VISIBLE);
            content_frame.setVisibility(View.GONE);
        } else if (id == R.id.nav_monitor) {
            toolbar.setSubtitle("监控管理");
            content_layout.setVisibility(View.GONE);
            content_frame.setVisibility(View.VISIBLE);
            Fragment fg = new MonitorFragment();
            fm.beginTransaction().replace(R.id.content_frame, fg).commit();
        } else if (id == R.id.nav_remote_control) {
            toolbar.setSubtitle("远程控制");
            content_layout.setVisibility(View.GONE);
            content_frame.setVisibility(View.VISIBLE);
            Fragment fg = new RemoteControlFragment();
            fm.beginTransaction().replace(R.id.content_frame, fg).commit();
        } else if (id == R.id.nav_tools) {
            toolbar.setSubtitle("调试工具");
            content_layout.setVisibility(View.GONE);
            content_frame.setVisibility(View.VISIBLE);
            Fragment fg = new DebugToolsFragment();
            fm.beginTransaction().replace(R.id.content_frame, fg).commit();
        } else if (id == R.id.nav_simulate) {
            toolbar.setSubtitle("模拟测试");
            content_layout.setVisibility(View.GONE);
            content_frame.setVisibility(View.VISIBLE);
            Fragment fg = new SimulateTestFragment();
            fm.beginTransaction().replace(R.id.content_frame, fg).commit();
        } else if (id == R.id.nav_about) {
            toolbar.setSubtitle("SmartMobileRobot");
            content_layout.setVisibility(View.GONE);
            content_frame.setVisibility(View.VISIBLE);
            Fragment fg = new AboutFragment();
            fm.beginTransaction().replace(R.id.content_frame, fg).commit();
        } else if (id == R.id.nav_send) {
            toolbar.setSubtitle("联系我们");
            content_layout.setVisibility(View.GONE);
            content_frame.setVisibility(View.VISIBLE);
            Fragment fg = new ContactUsFragment();
            fm.beginTransaction().replace(R.id.content_frame, fg).commit();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /////////////////////////////////////////我是分割线/////////////////////////////////////////

    private void startClient() {
        connect_state_tv.setText("服务器连接中...");
        connect_state_tv.setTextColor(Color.BLACK);
        isClientSocket_threadWorking = true;
        if (mClientSocket_thread == null) {
            mClientSocket_thread = new ClientSocket_thread();
            mClientSocket_thread.start();
        }

        isReceive_ThreadWorking = true;
        if (mReceive_Thread == null) {
            mReceive_Thread = new Receive_Thread();
            mReceive_Thread.start();
        }

        isConnected = true;
        connect_state_tv.setText("服务器已连接");
        connect_state_tv.setTextColor(Color.GREEN);
    }

    private void stopClient() {
        try {
            //发送数据
            outputStream.write(DISCONNECT.getBytes());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        isClientSocket_threadWorking = false;
        isReceive_ThreadWorking = false;
        mClientSocket_thread.interrupt();
        mClientSocket_thread = null;
        mReceive_Thread.interrupt();
        mReceive_Thread = null;
        isConnected = false;
        connect_state_tv.setText("连接已断开");
        connect_state_tv.setTextColor(Color.RED);
    }

    class ClientSocket_thread extends Thread {
        public void run()//重写Thread的run方法
        {
            try {
                inputStream = null;
                outputStream = null;
                clientSocket = new Socket(IP_ADDRESS_SERVER, Integer.valueOf(PORT_SERVER));
                inputStream = clientSocket.getInputStream();
                outputStream = clientSocket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            while (!isClientSocket_threadWorking) {
                try {
                    if (inputStream != null && outputStream != null) {
                        inputStream.close();
                        outputStream.close();
                        clientSocket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    class Receive_Thread extends Thread//继承Thread
    {
        public void run()//重写run方法
        {
            while (isReceive_ThreadWorking) {
                try {
                    final byte[] buf = new byte[1024];
                    final int len = inputStream.read(buf);
                    if (len == -1) {
                        break;
                    }
                    runOnUiThread(new Runnable() {
                        public void run() {
                            try {
                                data_from_server = new String(buf, 0, len, "utf8");
                                if (data_from_server.equals("nothing changed")) {
                                    return;
                                }
                                server_state_edt.getText().append(new String(buf, 0, len, "utf8"));
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            server_state_edt.getText().append("\n");
                        }
                    });

                    try {
                        //发送数据
                        outputStream.write(APP_ACK_STATE.getBytes());
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }


    ///////////////////////////////////////服务器数据库连接////////////////////////////////////////
    public void onConn(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                connect_state_tv.setText("数据库连接中...");
                connect_state_tv.setTextColor(Color.BLACK);
                mysql_conn = MySqlUtil.openConnection("jdbc:mysql://" + IP_ADDRESS_SERVER + "/smart_car", USER, PASSWORD);
                Log.i("onConn", "onConn");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mysql_conn == null) {
                            connect_state_tv.setText("数据库连接失败");
                            connect_state_tv.setTextColor(Color.RED);
                        } else {
                            connect_state_tv.setText("数据库已连接");
                            connect_state_tv.setTextColor(Color.GREEN);
                            try {
                                Thread.sleep(1);
                                connect_state_tv.setText("连接成功");
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            }
        }).start();
    }

//    public void onUpdate(View view) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                String sql = "update che_liang_info set name='test_liei' where name='lilei'";
//                MySqlUtil.execSQL(mysql_conn, sql);
//                Log.i("onUpdate", "onUpdate");
//            }
//        }).start();
//    }
//
//    public void onQuery(View view) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                Log.i("onQuery", "onQuery");
//                MySqlUtil.query(mysql_conn, "select * from che_liang_info");
//            }
//        }).start();
//    }

}
